package com.atguigu.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.wareVo.OrderVo;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * <p>Title: StockReleaseListener</p>
 * Description：
 * date：2020/7/3 23:56
 */
@Slf4j
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

	@Autowired
	private WareSkuService wareSkuService;

	/**
	 * 下单成功 库存解锁 接下来业务调用失败
	 *
	 *  只要解锁库存消息失败 一定要告诉服务解锁失败
	 */
	@RabbitHandler
	public void handleStockLockedRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
		/**
		 * 解锁库存
		 * 	查询数据库关系这个订单的详情
		 * 		有: 证明库存锁定成功
		 * 			1.没有这个订单, 必须解锁
		 * 			2.有这个订单 不是解锁库存
		 * 				订单状态：已取消,解锁库存
		 * 				没取消：不能解锁	;
		 * 		没有：就是库存锁定失败， 库存回滚了 这种情况无需回滚
		 */
		//1.查询没有解锁的库存信息
		try {

			System.out.println("收到解锁库存指令"+stockLockedTo);
			wareSkuService.unlockStock(stockLockedTo);
			channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		}

		catch (Exception e){
//TODO 告诉MQ解锁失败
			channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
			log.info("解锁库存失败" +e);
		}



	}
	@RabbitHandler
	public void handleOrderClose(OrderTo orderTo, Message message, Channel channel) throws IOException {
		System.out.println("订单关闭解锁库存。。。");
		try {
			wareSkuService.unlockStock(orderTo);
			channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		}catch (Exception e){
			channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
		}

	}
}
